import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Xiaoxi.module.css';
import { io } from 'socket.io-client';
import  {http,host,port} from '../utils/host'
function Xiaoxi() {
    const navigate = useNavigate();
    const [users, setUsers] = useState([]);
    const [groups, setGroups] = useState([]);
    const [schools, setSchools] = useState([]);
    const [selectedSchool, setSelectedSchool] = useState('');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [showMenu, setShowMenu] = useState(false);
    const [activeTab, setActiveTab] = useState('users'); // 'users' 或 'groups'
    const [showCreateGroup, setShowCreateGroup] = useState(false);
    const [selectedUsers, setSelectedUsers] = useState([]);
    const [groupName, setGroupName] = useState('');
    
    // 获取当前用户信息
    const getCurrentUser = () => {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            const parsed = JSON.parse(userInfo);
            return {
                _id: parsed.userId,
                schoolId: parsed.schoolId,
                username: parsed.username
            };
        }
        // 如果没有用户信息，使用默认值（仅用于测试）
        return {
            _id: '688cb2ff5e9bdf7c861dcd92', // 张三的ID
            schoolId: '688cb2ff5e9bdf7c861dcd90', // 测试大学的ID
            username: '张三'
        };
    };
    
    const currentUser = getCurrentUser();

    useEffect(() => {
        fetchSchools();
        fetchGroups();
        
        // 连接WebSocket
        const newSocket = io(`${http}${host}${port}`, {
            transports: ['websocket', 'polling'],
            reconnection: true,
            reconnectionAttempts: 5,
            reconnectionDelay: 1000
        });

        // 用户登录到WebSocket
        newSocket.emit('user_login', {
            userId: currentUser._id,
            username: currentUser.username
        });

        // 连接成功
        newSocket.on('connect', () => {
            console.log('消息列表WebSocket连接成功');
        });

        // 连接错误
        newSocket.on('connect_error', (error) => {
            console.error('消息列表WebSocket连接错误:', error);
        });

        // 监听群聊消息，更新群聊列表
        newSocket.on('receive_group_message', (message) => {
            console.log('收到群聊新消息，更新群聊列表:', message);
            // 刷新群聊列表以更新未读消息数
            fetchGroups();
        });

        return () => {
            newSocket.disconnect();
        };
    }, [currentUser._id, currentUser.username]);

    useEffect(() => {
        if (selectedSchool) {
            fetchUsers();
        }
    }, [selectedSchool]);

    // 点击外部关闭菜单
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showMenu && !event.target.closest(`.${styles.menuContainer}`)) {
                setShowMenu(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showMenu]);

    const fetchSchools = async () => {
        try {
            const response = await fetch(`${http}${host}${port}/school`);
            const data = await response.json();
            
            if (data.code === 200) {
                setSchools(data.data);
                
                // 根据当前用户的学校ID自动选择对应的学校
                const currentUserSchoolId = currentUser.schoolId;
                const userSchool = data.data.find(school => school._id === currentUserSchoolId);
                
                if (userSchool) {
                    // 找到当前用户对应的学校，选择它
                    setSelectedSchool(userSchool._id);
                    console.log('自动选择用户所在学校:', userSchool.name);
                } else {
                    // 如果没找到，则选择第一个学校作为默认值
                    if (data.data.length > 0) {
                        setSelectedSchool(data.data[0]._id);
                        console.log('未找到用户学校，选择默认学校:', data.data[0].name);
                    }
                }
            }
        } catch (error) {
            console.error('获取学校列表失败:', error);
        }
    };

    const fetchUsers = async () => {
        if (!selectedSchool) return;
        
        try {
            setLoading(true);
            setError('');
            
            console.log('当前用户信息:', currentUser);
            console.log('选择的学校ID:', selectedSchool);
            console.log('请求URL:', `${http}${host}${port}/api/messages/users/${selectedSchool}?currentUserId=${currentUser._id}`);

            const response = await fetch(
                `${http}${host}${port}/api/messages/users/${selectedSchool}?currentUserId=${currentUser._id}`
            );
            const data = await response.json();
            
            console.log('API响应:', data);
            
            if (data.code === 200) {
                setUsers(data.data);
            } else {
                setError(data.message || '获取用户列表失败');
                console.error('获取用户列表失败:', data.message);
            }
        } catch (error) {
            setError('网络错误，请检查后端服务是否启动');
            console.error('获取用户列表错误:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchGroups = async () => {
        try {
            const response = await fetch(`${http}${host}${port}/groups?userId=${currentUser._id}`);
            const data = await response.json();
            
            console.log('群聊列表响应:', data);
            
            if (data.code === 200) {
                setGroups(data.data);
                // 调试：查看第一个群聊的数据结构
                if (data.data && data.data.length > 0) {
                    console.log('第一个群聊数据结构:', data.data[0]);
                    console.log('memberUnreadCount类型:', typeof data.data[0].memberUnreadCount);
                    console.log('memberUnreadCount值:', data.data[0].memberUnreadCount);
                }
            } else {
                console.error('获取群聊列表失败:', data.message);
            }
        } catch (error) {
            console.error('获取群聊列表错误:', error);
        }
    };

    const handleUserClick = async (user) => {
        try {
            console.log('点击用户:', user);
            
            // 直接导航到聊天页面，让聊天组件自己处理会话创建
            navigate(`/chat/new/${user._id}`);
        } catch (error) {
            console.error('导航到聊天页面失败:', error);
            alert('进入聊天失败，请重试');
        }
    };

    const handleGroupClick = async (group) => {
        try {
            console.log('点击群聊:', group);
            
            // 导航到群聊页面
            navigate(`/group/${group._id}`);
        } catch (error) {
            console.error('导航到群聊页面失败:', error);
            alert('进入群聊失败，请重试');
        }
    };

    const handleSchoolChange = (schoolId) => {
        setSelectedSchool(schoolId);
    };

    const handleMenuClick = (action) => {
        setShowMenu(false);
        // 处理菜单点击
        switch (action) {
            case 'createGroup':
                setShowCreateGroup(true);
                break;
            case 'payment':
                alert('付钱/收钱功能');
                break;
            case 'bus':
                alert('乘车码功能');
                break;
            case 'assistant':
                alert('智能助理功能');
                break;
            default:
                break;
        }
    };

    const handleCreateGroup = async () => {
        if (!groupName.trim() || selectedUsers.length === 0) {
            alert('请输入群聊名称并选择至少一个成员');
            return;
        }

        try {
            const response = await fetch(`${http}${host}${port}/groups`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: groupName.trim(),
                    members: [...selectedUsers, currentUser._id],
                    createdBy: currentUser._id
                })
            });

            const data = await response.json();
            
            if (data.code === 200) {
                alert('群聊创建成功！');
                setShowCreateGroup(false);
                setGroupName('');
                setSelectedUsers([]);
                fetchGroups(); // 刷新群聊列表
            } else {
                alert(data.message || '创建群聊失败');
            }
        } catch (error) {
            console.error('创建群聊失败:', error);
            alert('创建群聊失败，请重试');
        }
    };

    const handleUserSelect = (userId) => {
        setSelectedUsers(prev => {
            if (prev.includes(userId)) {
                return prev.filter(id => id !== userId);
            } else {
                return [...prev, userId];
            }
        });
    };

    const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        const now = new Date();
        const diffInHours = (now - date) / (1000 * 60 * 60);
        
        if (diffInHours < 24) {
            return date.toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        } else {
            return date.toLocaleDateString('zh-CN', { 
                month: '2-digit', 
                day: '2-digit' 
            });
        }
    };

    const getUnreadCount = (group) => {
        // 使用后端返回的unreadCount字段
        return group.unreadCount || 0;
    };

    return (
        <div className={styles.container}>
            {/* 顶部标题栏 */}
            <div className={styles.header}>
                <div className={styles.title}>消息</div>
                <div className={styles.headerRight}>
                    <div className={styles.searchBar}>
                        <span className={styles.searchIcon}>🔍</span>
                        <span className={styles.searchText}>搜索</span>
                    </div>
                    <div className={styles.menuContainer}>
                        <div 
                            className={styles.settingsIcon}
                            onClick={() => setShowMenu(!showMenu)}
                        >
                            ⚙️
                        </div>
                        {showMenu && (
                            <div className={styles.dropdownMenu}>
                                <div 
                                    className={styles.menuItem}
                                    onClick={() => handleMenuClick('createGroup')}
                                >
                                    👥 创建群聊
                                </div>
                                <div 
                                    className={styles.menuItem}
                                    onClick={() => handleMenuClick('payment')}
                                >
                                    💰 付钱/收钱
                                </div>
                                <div 
                                    className={styles.menuItem}
                                    onClick={() => handleMenuClick('bus')}
                                >
                                    🚌 乘车码
                                </div>
                                <div 
                                    className={styles.menuItem}
                                    onClick={() => handleMenuClick('assistant')}
                                >
                                    🤖 智能助理
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

        

            {/* 功能图标区域 */}
            <div className={styles.iconRow}>
                <div className={styles.iconItem}>
                    <div className={`${styles.icon} ${styles.fansIcon}`}>
                        <span className={styles.iconSymbol}>👤</span>
                    </div>
                    <span className={styles.iconLabel}>粉丝</span>
                </div>
                <div className={styles.iconItem}>
                    <div className={`${styles.icon} ${styles.mentionsIcon}`}>
                        <span className={styles.iconSymbol}>@</span>
                    </div>
                    <span className={styles.iconLabel}>@我的</span>
                </div>
                <div className={styles.iconItem}>
                    <div className={`${styles.icon} ${styles.commentsIcon}`}>
                        <span className={styles.iconSymbol}>💬</span>
                    </div>
                    <span className={styles.iconLabel}>评论</span>
                </div>
                <div className={styles.iconItem}>
                    <div className={`${styles.icon} ${styles.likesIcon}`}>
                        <span className={styles.iconSymbol}>👍</span>
                    </div>
                    <span className={styles.iconLabel}>赞</span>
                </div>
            </div>

            {/* 标签页切换 */}
            <div className={styles.tabContainer}>
                <div 
                    className={`${styles.tab} ${activeTab === 'users' ? styles.activeTab : ''}`}
                    onClick={() => setActiveTab('users')}
                >
                    联系人
                </div>
                <div 
                    className={`${styles.tab} ${activeTab === 'groups' ? styles.activeTab : ''}`}
                    onClick={() => setActiveTab('groups')}
                >
                    群聊
                </div>
            </div>

            {/* 用户列表区域 */}
            {activeTab === 'users' && (
                <div className={styles.userList}>
                    {loading ? (
                        <div className={styles.loading}>
                            <div className={styles.loadingText}>加载中...</div>
                        </div>
                    ) : error ? (
                        <div className={styles.errorState}>
                            <div className={styles.errorText}>{error}</div>
                            <button 
                                className={styles.retryButton}
                                onClick={fetchUsers}
                            >
                                重试
                            </button>
                        </div>
                    ) : users.length > 0 ? (
                        users.map((user) => (
                            <div 
                                key={user._id} 
                                className={styles.userItem}
                                onClick={() => handleUserClick(user)}
                            >
                                <div className={styles.userAvatar}>
                                    {user.avatarImage ? (
                                        <img src={user.avatarImage} alt="用户头像" />
                                    ) : (
                                        <div className={styles.defaultUserAvatar}>
                                            {user.username?.charAt(0) || 'U'}
                                        </div>
                                    )}
                                </div>
                                <div className={styles.userInfo}>
                                    <div className={styles.userName}>{user.username}</div>
                                    <div className={styles.userStudentId}>{user.studentId}</div>
                                    {user.qianming && (
                                        <div className={styles.userSignature}>{user.qianming}</div>
                                    )}
                                </div>
                                <div className={styles.userAction}>
                                    <span className={styles.chatButton}>💬</span>
                                </div>
                            </div>
                        ))
                    ) : (
                        <div className={styles.emptyState}>
                            <div className={styles.emptyText}>该学校暂无其他用户</div>
                        </div>
                    )}
                </div>
            )}

            {/* 群聊列表区域 */}
            {activeTab === 'groups' && (
                <div className={styles.groupList}>
                    {groups.length > 0 ? (
                        groups.map((group) => {
                            try {
                                return (
                                    <div 
                                        key={group._id} 
                                        className={styles.groupItem}
                                        onClick={() => handleGroupClick(group)}
                                    >
                                        <div className={styles.groupAvatar}>
                                            <div className={styles.defaultGroupAvatar}>
                                                👥
                                            </div>
                                        </div>
                                        <div className={styles.groupInfo}>
                                            <div className={styles.groupName}>{group.name}</div>
                                            <div className={styles.groupMembers}>
                                                {group.members?.length || 0} 人
                                            </div>
                                            <div className={styles.groupTime}>
                                                {formatTime(group.createdAt)}
                                            </div>
                                        </div>
                                        <div className={styles.groupAction}>
                                            {getUnreadCount(group) > 0 && (
                                                <div className={styles.unreadBadge}>
                                                    {getUnreadCount(group)}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                );
                            } catch (error) {
                                console.error('渲染群聊项时出错:', error, group);
                                return null;
                            }
                        })
                    ) : (
                        <div className={styles.emptyState}>
                            <div className={styles.emptyText}>暂无群聊</div>
                        </div>
                    )}
                </div>
            )}

            {/* 创建群聊弹窗 */}
            {showCreateGroup && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h3>创建群聊</h3>
                            <button 
                                className={styles.closeButton}
                                onClick={() => setShowCreateGroup(false)}
                            >
                                ✕
                            </button>
                        </div>
                        <div className={styles.modalContent}>
                            <div className={styles.inputGroup}>
                                <label>群聊名称</label>
                                <input
                                    type="text"
                                    value={groupName}
                                    onChange={(e) => setGroupName(e.target.value)}
                                    placeholder="请输入群聊名称"
                                    className={styles.input}
                                />
                            </div>
                            <div className={styles.inputGroup}>
                                <label>选择成员</label>
                                <div className={styles.userSelection}>
                                    {users.map((user) => (
                                        <div 
                                            key={user._id}
                                            className={`${styles.userSelectionItem} ${
                                                selectedUsers.includes(user._id) ? styles.selected : ''
                                            }`}
                                            onClick={() => handleUserSelect(user._id)}
                                        >
                                            <div className={styles.userSelectionAvatar}>
                                                {user.avatarImage ? (
                                                    <img src={user.avatarImage} alt="用户头像" />
                                                ) : (
                                                    <div className={styles.defaultUserAvatar}>
                                                        {user.username?.charAt(0) || 'U'}
                                                    </div>
                                                )}
                                            </div>
                                            <div className={styles.userSelectionName}>
                                                {user.username}
                                            </div>
                                            {selectedUsers.includes(user._id) && (
                                                <div className={styles.checkmark}>✓</div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                        <div className={styles.modalFooter}>
                            <button 
                                className={styles.cancelButton}
                                onClick={() => setShowCreateGroup(false)}
                            >
                                取消
                            </button>
                            <button 
                                className={styles.createButton}
                                onClick={handleCreateGroup}
                            >
                                创建
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default Xiaoxi;